package org.acooly.secretbox.service.impl;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.acooly.android.utils.StringUtils;
import org.acooly.secretbox.service.SettingService;
import org.acooly.secretbox.service.domain.Setting;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class SettingServiceImpl extends SQLiteOpenHelper implements SettingService {

	private static final String DATABASE_NAME = "setting.db";
	private static final String TABLE_NAME = "SETTING";
	private static final String TABLE_CREATE = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME
			+ "(ID INTEGER PRIMARY KEY AUTOINCREMENT, KEY text not null,VALUE text not null,comments text );";

	public SettingServiceImpl(Context context) {
		super(context, DATABASE_NAME, null, 1);
	}

	@Override
	public Setting get(String key) {
		SQLiteDatabase db = getReadableDatabase();
		try {
			Cursor cur = db.rawQuery("select * from " + TABLE_NAME + " where key = ?", new String[] { key });
			Setting setting = null;
			if (cur.moveToNext()) {
				setting = new Setting(cur.getInt(0), cur.getString(1), cur.getString(2), cur.getString(3));
			}
			cur.close();
			return setting;
		} catch (Exception e) {
			Log.e("SettingService", e.getMessage());
			throw new RuntimeException("获取参数失败:" + e.getMessage());
		} finally {
			db.close();
		}
	}

	@Override
	public String getValue(String key) {
		return get(key).getValue();
	}

	@Override
	public List<String> getListValue(String key) {
		Setting setting = get(key);
		if (setting != null) {
			return StringUtils.toList(setting.getValue());
		}
		return new LinkedList<String>();
	}

	@Override
	public void set(String key, String value) {
		Setting setting = get(key);
		if (setting == null) {
			setting = new Setting(key, value);
		} else {
			setting.setValue(value);
		}

		save(setting);
	}

	@Override
	public List<Setting> list() {
		SQLiteDatabase db = null;
		try {
			String sql = "select * from " + TABLE_NAME + " order by id desc";
			db = getReadableDatabase();
			Cursor cur = db.rawQuery(sql, null);
			List<Setting> settings = new LinkedList<Setting>();
			while (cur.moveToNext()) {
				settings.add(new Setting(cur.getInt(0), cur.getString(1), cur.getString(2), cur.getString(3)));
			}
			cur.close();
			return settings;
		} catch (Exception e) {
			Log.e("SettingService", e.getMessage());
			throw new RuntimeException("查询设置列表失败:" + e.getMessage());
		} finally {
			db.close();
		}
	}

	@Override
	public List<Map<String, Object>> listToMap() {
		List<Setting> settings = list();
		List<Map<String, Object>> listMaps = new LinkedList<Map<String, Object>>();
		for (Setting setting : settings) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put(setting.getKey(), setting.getValue());
			listMaps.add(map);
		}
		return listMaps;
	}

	@Override
	public void save(Setting setting) {
		SQLiteDatabase db = null;
		try {

			ContentValues values = new ContentValues();
			values.put("KEY", setting.getKey());
			values.put("VALUE", setting.getValue());
			values.put("comments", setting.getComments());
			db = this.getWritableDatabase();
			if (setting.getId() == 0) {
				// create
				db.insert(TABLE_NAME, null, values);
			} else {
				// update
				db.update(TABLE_NAME, values, "id=?", new String[] { String.valueOf(setting.getId()) });
			}

		} catch (Exception e) {
			Log.e("SettingService", e.getMessage());
			throw new RuntimeException("参数保存失败:" + e.getMessage());
		} finally {
			if (db.isOpen()) {
				db.close();
			}
		}
	}

	@Override
	public void delete(String key) {
		SQLiteDatabase db = null;
		try {
			db = getWritableDatabase();
			db.delete(TABLE_NAME, " key = " + key, null);
		} catch (Exception e) {
			Log.e("AccountService", e.getMessage());
			throw new RuntimeException("删除账户失败");
		} finally {
			if (db.isOpen()) {
				db.close();
			}
		}
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		Log.i(DATABASE_NAME, TABLE_CREATE);
		db.execSQL(TABLE_CREATE);
	}

	@Override
	public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
		// TODO Auto-generated method stub

	}

}
